<template>
	<div class="wareHous-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item label="序号">
					<el-input v-model="state.queryParams.materialCode" placeholder="物料编码" clearable />
				</el-form-item>
				<el-form-item label="批次">
					<el-input v-model="state.queryParams.batch" placeholder="批次" clearable />
				</el-form-item>
				<el-form-item label="托盘">
					<el-input v-model="state.queryParams.palcode" placeholder="母托盘" clearable />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery"> 查询
						</el-button>
						<el-button icon="ele-Refresh" @click="resetQuery"> 重置 </el-button>
					</el-button-group>
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Plus" @click="addWare">添加</el-button>
						<el-button type="primary" icon="ele-Plus" @click="updatestatus(1)">解冻</el-button>

						<el-button type="primary" icon="ele-Plus" @click="updatestatus(2)">冻结</el-button>
					</el-button-group>
					<el-button-group>


						<!-- <el-button type="primary" icon="ele-Download" @click="downloadTemplate"
				>模版</el-button> -->

						<el-button type="primary" icon="ele-Download" @click="exportDate">导出</el-button>
						<el-button type="danger" icon="ele-Warning" @click="batchDeleteInventory">批量删除</el-button>

					</el-button-group>
					<el-upload class="upload-demo" :before-upload="beforeUpload" :http-request="handleUpload"
						:show-file-list="false" :on-success="handleUploadSuccess" :on-error="handleUploadError">
						<el-button icon="ele-Upload">导入</el-button>
					</el-upload>
				</el-form-item>


			</el-form>
		</el-card>

		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table :data="state.InventoryData" style="width: 100%" @selection-change="handleSelectionChange"
				v-loading="state.loading" border :default-sort="{ prop: 'status', order: 'ascending' }
					">

				<el-table-column type="selection" prop="id" width="55" align="center" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="warehousePositionCode" label="库位" align="center" show-overflow-tooltip />
				<el-table-column prop="palcode" label="托盘" align="center" show-overflow-tooltip />
				<el-table-column prop="status" label="库存状态" width="80" align="center">
					<template #default="scope">
						<el-tag v-if="scope.row.status === 0"> 正常 </el-tag>
						<el-tag v-if="scope.row.status === 1"> 冻结 </el-tag>
						<el-tag v-if="scope.row.status === 2"> 暂存入库 </el-tag>
						<el-tag v-if="scope.row.status === 3"> 出库完成 </el-tag>
						<!-- <el-tag type="danger" v-else> 其他 </el-tag> -->
					</template>
				</el-table-column>
				<el-table-column prop="boxCode" label="箱条码" align="center" show-overflow-tooltip />
				<el-table-column prop="materialCode" label="物料编码" align="center" show-overflow-tooltip />
				<el-table-column prop="materialName" label="物料名称" align="center" show-overflow-tooltip />
				<el-table-column prop="batch" label="批次" align="center" show-overflow-tooltip />
				<el-table-column prop="reference" label="参考号" align="center" show-overflow-tooltip />
				<el-table-column prop="number" label="数量" align="center" show-overflow-tooltip />
				<el-table-column prop="dateofReceipt" label="收货日期" align="center" show-overflow-tooltip />
				<!-- <el-table-column prop="subtray" label="子托盘" align="center" show-overflow-tooltip /> -->

				<el-table-column prop="createTime" label="创建时间" width="0" align="center" show-overflow-tooltip />

				<el-table-column label="操作" width="0" fixed="right" align="center" show-overflow-tooltip>
					<template #default="scope">
						<el-button icon="ele-Edit" size="small" text type="primary"
							@click="openEditWarehous(scope.row)"> 编辑 </el-button>
						<el-button size="small" text type="danger" @click="delWarehous(scope.row)"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:currentPage="state.tableParams.page" v-model:page-size="state.tableParams.pageSize"
				:total="state.tableParams.total" :page-sizes="[10, 20, 50, 100]" size="small" background
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
		</el-card>

		<EditInventory ref="editInventoryRef" :title="state.editWarehousTitle" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="Inventory">
import { onMounted, computed, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EditInventory from './component/editInventory.vue';
import { getAPI } from '/@/utils/axios-utils';
import { InventoryManagementApi, BatchUpdateStatusApi, InventoryManagementexportApi, InventoryManagementinportApi, DownloadManagemenApi,BatchDeleteInventoryApi } from '/@/api-services/apis/warehouse-inventory-api'; // 导入 API 服务
import { InventoryManagement, DeleteInventoryManagementInput } from '/@/api-services/models/warehouse-inventory-input'; // 导入库位实体
import { WarehouseInput } from '/@/api-services/models/warehouse-input'; // 导入托盘码和批次实体添加编辑下拉
import { error } from 'console';
import { DeleteCodeGenInput } from '/@/api-services';

import { downloadByData, getFileName } from '/@/utils/download';

//import { Inventory } from '@vueuse/core';
// ...其他导入

const editInventoryRef = ref<InstanceType<typeof EditInventory>>();
const state = reactive({
	loading: false,
	InventoryData: [] as Array<InventoryManagement>,
	wareHousData: [] as Array<WarehouseInput>,
	queryParams: {
		materialCode: undefined,
		batch: undefined,
		palcode: undefined,
	},
	tableParams: {
		page: 1,
		pageSize: 50,
		total: 0,
	},
	editWarehousTitle: '',

});

onMounted(async () => {
	handleQuery();
});




// 查询操作
const handleQuery = async () => {
	state.loading = true;
	try {

		const res = await getAPI(InventoryManagementApi).apiInventoryManagementPagePost({
			...state.queryParams,
			page: state.tableParams.page,
			pageSize: state.tableParams.pageSize,
		});
		state.InventoryData = res.data.result?.items || [];
		state.tableParams.total = res.data?.result?.total ?? 0;

	} catch {
		state.wareHousData = [];
		state.tableParams.total = 0;
	}

	finally {
		state.loading = false;

	}
};

// 重置操作
const resetQuery = () => {
	state.queryParams.materialCode = undefined;
	state.queryParams.batch = undefined;
	handleQuery();
};

// 打开新增页面
const addWare = () => {
	const addData = {
		warehousCode: undefined,
		code: undefined,
		poiint: undefined,
		isenable: 0,
		// wareHousData: [] as Array<WarehouseInput>,
	};
	state.editWarehousTitle = '新增';
	editInventoryRef.value?.openDialog(addData);
};
const multipleSelection = ref<DeleteInventoryManagementInput[]>([]);

const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val;
};
//获取选中行的信息
// 该函数用于返回选中行的多个 status 值status
const status = computed(() => multipleSelection.value.map(item => ({ status: item.status })));


// 获取选中行的 ID
const selectedIds = computed(() => multipleSelection.value.map(item => ({ id: item.id })));



const batchDeleteInventory = async () => {
	if (selectedIds.value.length === 0) {
		ElMessage.warning('请选择要删除的行');
		return;
	}
	console.log(selectedIds.value);
	try {
		await BatchDeleteInventoryApi(selectedIds.value);
		handleQuery(); // 刷新表格数据
		ElMessage.success('批量删除成功');
	} catch (error) {
		ElMessage.error('批量删除失败');
		}
	};

const updatestatus = async (c: number) => {
	console.log(status.value);
	// 获取选中行的信息
	const selectedIdsValue = selectedIds.value;
	if (selectedIdsValue.length === 0) {
		ElMessage.error('请选择要操作的库存记录');
		return;
	}
	if (c == 1) {
		// 检查 status 中是否包含 0
		const hasZeroStatus = status.value.some((item: { status: number }) => item.status === 1);
		if (hasZeroStatus) {
			ElMessage.error('选中记录中存在状态为正常的记录，无法执行解冻操作');
			return;
		}
		ElMessageBox.confirm(`确定解冻选中的库存记录吗？`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(async () => {
				try {
					await BatchUpdateStatusApi(selectedIdsValue);
					handleQuery();
					ElMessage.success('解冻成功');
				} catch (error) {
					ElMessage.error('解冻失败，请稍后重试');
				}
			})
	}
	else if (c == 2) {

		const hasZeroStatus = status.value.some(item => item.status === 0);
		if (hasZeroStatus) {
			ElMessage.error('选中记录中存在状态为冻结的记录，无法执行冻结操作');
			return;
		}
		ElMessageBox.confirm(`确定冻结选中的库存记录吗？`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(async () => {
				try {
					// 根据错误信息，接口期望接收一个 JSON 数组，因此直接传入 requestData.id 数组
					await getAPI(InventoryManagementApi).apiInventoryManagementStatusPost(selectedIdsValue);
					handleQuery();
					ElMessage.success('冻结成功');
				}
				catch (error) {
					ElMessage.error('冻结失败，请稍后重试');
				}
			})
	}

}



// 关闭新增页面
const closeAddDialog = () => {
	editInventoryRef.value?.openDialog(false);
};



// 打开编辑页面
const openEditWarehous = (row: any) => {
	state.editWarehousTitle = '编辑';
	editInventoryRef.value?.openDialog(row);
};

// 删除操作
const delWarehous = (row: any) => {
	ElMessageBox.confirm(`确定删除【${row.materialCode}】`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await getAPI(InventoryManagementApi).apiInventoryManagementDeletePost({ id: row.id, status: 0 });
				handleQuery();
				ElMessage.success('删除成功');
			} catch (error) {
				ElMessage.error('删除失败，请稍后重试');
			}
		})
		.catch(() => {
			ElMessage.info('已取消删除');
		});
};

const exportDate = async () => {
	try {
		state.loading = true;
		// 通常导出文件时需要设置 responseType 为 'blob'，以正确处理二进制数据
		// 为了解决类型不匹配问题，将 responseType 单独传递
		const config = { responseType: 'blob' };
		var res = await InventoryManagementexportApi(state.queryParams);
		state.loading = false;
		var fileName = getFileName(res.headers);
		// 假设增加一些日志记录，方便调试
		console.log('准备开始下载文件，文件数据:', res.data, '文件名:', fileName);
		downloadByData(res.data as any, fileName);
		ElMessage.success('导出成功' + fileName);
	}
	catch (error) {
		state.loading = false;
		ElMessage.error('导出失败');
	}
};

// #region 导入
// 上传前校验
const beforeUpload = (file: File) => {
	const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
		file.type === 'application/vnd.ms-excel'
	if (!isExcel) {
		ElMessage.error('只能上传 Excel 文件!')
		return false
	}
	return true
}
// 自定义上传方法
const handleUpload = async (options: any) => {
	const formData = new FormData()
	formData.append('file', options.file)
	// 这里调用你的上传API
	console.log('handleUpload', formData);
	try {

		const response = await InventoryManagementinportApi(formData).then((response) => {
			console.log('response', response);
			handleUploadSuccess(response);

		})

	} catch (error) {

		console.log('error', error);
		handleUploadError(error);
	}
};


// 上传成功回调
const handleUploadSuccess = async (response: any) => {
	console.log('response', response);
	if (response.status === 200) {
		ElMessage.success('导入成功')
		handleQuery() // 刷新表格数据
	}
	else {
		ElMessage.error(response.message || '导入失败')
	}
};

// 上传失败回调
const handleUploadError = (error: any) => {
	ElMessage.error(error.message || '导入失败' + error.message)
};

//下载文件
const downloadTemplate = async () => {
	try {
		DownloadManagemenApi().then((response) => {

			const blob = new Blob([response.data])
			const fileName = getFileName(response.headers);
			downloadByData(response.data as any, fileName);

			ElMessage.success(`下载成功${fileName}`);
		}); // 调用下载模板的API

	} catch (error) {
		ElMessage.error('下载失败');
	}
};

// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
	state.tableParams.page = val;
	handleQuery();
};
</script>
